package com;

import com.Enum.LoggerEnum;
import com.api.Impl.DebugLogHandler;
import com.api.Impl.ErrorLogHandler;
import com.api.Impl.InfoLogHandler;
import com.api.Impl.WarningLogHandler;
import com.api.LogHandler;

import java.util.ArrayList;
import java.util.List;

public class LoggerChain implements LogHandler {
    private int currentPosition = 0;
    private List<LogHandler> handlers = new ArrayList<>();

    // 初始化日志责任链时可以结合创建型设计模式来动态实现，符合开闭原则
    public LoggerChain() {
        // 自动创建并排序处理器，按优先级从低到高
        handlers.add(new InfoLogHandler());
        handlers.add(new DebugLogHandler());
        handlers.add(new ErrorLogHandler());
        handlers.add(new WarningLogHandler());
    }

    // 处理日志
    public void log(LoggerEnum logLevel, String message) {
        this.handleLog(logLevel,message,null);
    }

    @Override
    public void handleLog(LoggerEnum logLevel, String message, LogHandler nextHandler) {
        if (currentPosition == handlers.size()) {
            // 退出责任链
            currentPosition = 0;
        }else{
            LogHandler firstHandler = handlers.get(currentPosition++);
            firstHandler.handleLog(logLevel, message, this);
        }
    }

}

